package com.malamute.system.aop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;

import com.malamute.core.constant.SystemConstant;
import com.malamute.core.entity.BaseEntity;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @author aceguan
 * 
 */
public class CrudAspect {

	public Logger log = Logger.getLogger(CrudAspect.class);

	/**
	 * @param jp
	 *            插入之前需要切入的节点
	 */
	public void doBeforeSave(JoinPoint jp) {

		log.info("doBeforeSave..................");
		if (jp.getArgs().length > 0) {
			Object object = jp.getArgs()[0];
			log.info(object instanceof BaseEntity);
			if (object instanceof BaseEntity) {
				BaseEntity entity = (BaseEntity) object;
				entity.setCreator(getCurrentUser());
				entity.setCreateTime(new Date());
			}
		}
	}

	private String getCurrentUser() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(ServletActionContext.HTTP_REQUEST);
		System.out.println(request);
		HttpSession session = request.getSession();
		String currentUser = (String) session
				.getAttribute(SystemConstant.SES_USER_LOGIN);
		if (currentUser == null) {
			currentUser = "guest";
		}
		return currentUser;
	}

	/**
	 * @param jp
	 *            修改之前需要切入的节点
	 */
	public void doBeforeUpdate(JoinPoint jp) {
		log.info("doBeforeUpdate....................................");
		log.info("jp.getClass().getName():" + jp.getClass().getName());
		log.info("jp.getSignature().getName():" + jp.getSignature().getName());
		log.info("jp.getArgs().getClass():" + jp.getArgs().getClass());
		log.info("jp.getThis():" + jp.getThis());
		log.info("jp.getTarget():" + jp.getTarget());
		log.info("jp.getArgs():" + jp.getArgs().length);
		if (jp.getArgs().length > 0) {
			Object object = jp.getArgs()[0];
			log.info(object instanceof BaseEntity);
			if (object instanceof BaseEntity) {
				BaseEntity entity = (BaseEntity) object;
				entity.setModify(getCurrentUser());
				entity.setModifyTime(new Date());
			}
		}

	}

}
